package org.lucava.boatskeeper.client;

import org.lucava.boatskeeper.shared.Boat;
import org.lucava.boatskeeper.shared.FieldVerifier;
import org.lucava.boatskeeper.shared.Localisation;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class BoatsKeeper implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final BoatsKeeperServiceAsync greetingService = GWT
			.create(BoatsKeeperService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button addButton = new Button("Add Boat");
		final TextBox nameField = new TextBox();
		nameField.setText("GWT User");
		final TextBox typeField = new TextBox();
		final TextBox descriptionField = new TextBox();
		final TextBox latitudeField = new TextBox();
		final TextBox longitudeField = new TextBox();
		final Label errorLabel = new Label();

		// We can add style names to widgets
		addButton.addStyleName("addButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("rootPane").add(nameField);
		RootPanel.get("rootPane").add(typeField);
		RootPanel.get("rootPane").add(descriptionField);
		RootPanel.get("rootPane").add(latitudeField);
		RootPanel.get("rootPane").add(longitudeField);

		RootPanel.get("rootPane").add(addButton);
		RootPanel.get("rootPane").add(errorLabel);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label boatToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending boat to the server:</b>"));
		dialogVPanel.add(boatToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox String greetServer(String name)
		// throws IllegalArgumentException;
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				addButton.setEnabled(true);
				addButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				addBoatToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					addBoatToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void addBoatToServer() {
				// First, we validate the boat name.
				errorLabel.setText("");
				String boatName = nameField.getText();
				if (!FieldVerifier.isValidName(boatName)) {
					errorLabel.setText("Please enter at least four characters");
					return;
				}

				// Création du bateau
				Boat newBoat = new Boat();
				newBoat.setName(boatName);
				newBoat.setType(typeField.getText());
				newBoat.setDescription(descriptionField.getText());

				// Récupération de la position du bateau
				float latitude = 0.0f;
				try {
					latitude = Float.parseFloat(latitudeField.getText());
				} catch (Exception e) {
					errorLabel.setText("Invalid Latitude!");
					return;
				}

				float longitude = 0.0f;
				try {
					longitude = Float.parseFloat(longitudeField.getText());
				} catch (Exception e) {
					errorLabel.setText("Invalid Longitude!");
					return;
				}

				newBoat.setLocalisation(new Localisation(latitude, longitude));

				// Then, we send the input to the server.
				addButton.setEnabled(false);

				serverResponseLabel.setText("");

				greetingService.addBoat(newBoat, new AsyncCallback<String>() {
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
						dialogBox.setText("Remote Procedure Call - Failure");
						serverResponseLabel
								.addStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(SERVER_ERROR);
						dialogBox.center();
						closeButton.setFocus(true);
					}

					public void onSuccess(String result) {
						dialogBox.setText("Remote Procedure Call");
						serverResponseLabel
								.removeStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(result);
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		addButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
	}
}
